using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

using System.Text.RegularExpressions;

public partial class BusinessUnitConfig : System.Web.UI.Page
{
    BusinessUnit.Access ACS;
    BusinessUnit.LoadToTreeView LTV;
    HDDatabase HDD;
    HtmlForm frmObj;
    string str_QryStr = "";
    string str_UserId = "";
    string strErrMessage = "";
    protected void Page_PreInit(object sender, EventArgs e)
    {
        this.Theme = Session["Theme"].ToString();
        this.Title = "MaxBlox";
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        security hdds = new security();

        if (Session["userid"] == null)
            Response.Redirect(hdds.SessionExpiryURL);
        if (Session["userid"].ToString() == "")
            Response.Redirect(hdds.SessionExpiryURL);
        Lbl_hierarchy_level.Visible = false;
        DD_hierarchy_level.Visible = false;
        this.HDD = new HDDatabase();
        this.str_UserId = Session["userid"].ToString();
        //this.str_QryStr = "london_stores";
        if (this.Master.FindControl("Form1") != null)
        {
            frmObj = (HtmlForm)this.Master.FindControl("Form1");
        }
        ScreenReader SR = new ScreenReader();
        if (Request.QueryString["BuId"] != null)
        {
            this.str_QryStr = this.HDD.GetColumnValue("sy_bu_unit", "af_row_id", "af_row_id='" + Request.QueryString["BuId"] + "'");
            this.btnSave.Visible = false;
            this.btnSaveNew.Visible = false;
            TB_business_unit.Enabled = false;
        }
        else if (Request.QueryString["PK"] != null)
        {

            this.str_QryStr = Request.QueryString["PK"];
            this.btnSave.Visible = false;
            TB_business_unit.Enabled = false;
            this.btnSaveNew.Visible = false;
            lblHeader.Text = "Business Unit - Edit";
        }
        else
        {
            HF_owner_id.Value = Session["user_afrowid"].ToString();
            TB_owner_id.Text = Session["userid"].ToString();
            ps_rowkey.Value = SR.getHashKey();
            this.btnUpdate.Visible = false;
            lblHeader.Text = "Business Unit - Add";
        }
        if (Request.QueryString["CPY"] != null)
        {
            TB_business_unit.Enabled = true;
            this.btnSave.Visible = true;

            this.btnSaveNew.Visible = true;
        }
        isViewMode();
        LoadBusinessUnit();
    }
    private void isViewMode()
    {
        if (HttpContext.Current.Request.QueryString["VMODE"] != null)
            if (HttpContext.Current.Request.QueryString["VMODE"] == "1")
            {
                DynamicDisplayI ddi = new DynamicDisplayI();
                HtmlTable ht = (HtmlTable)frmObj.FindControl("ContentPlaceHolder3").FindControl("TABLE1");
                ddi.disableControls(ht);
                ddi = null;
                lblHeader.Text = "Business Unit - View";

            }
    }
    private void LoadBusinessUnit()
    {
        this.ACS = new BusinessUnit.Access(this.str_UserId, this.HDD.GetConnection().ConnectionString, "");
        DataTable dt_BuUnit = this.ACS.BusinessUnitsTable;
        if (!IsPostBack)
        {
            this.LoadBuData(dt_BuUnit);
        }
        this.LTV = new BusinessUnit.LoadToTreeView();
        this.LTV.ShowCount = true;
        if (HttpContext.Current.Request.QueryString["VMODE"] != null)
        {
            if (HttpContext.Current.Request.QueryString["VMODE"] == "1")
            {
                this.LTV.LoadTreeView(tv_Bu, dt_BuUnit, HttpContext.Current.Request.CurrentExecutionFilePath + "?VMODE=1&BuId=", str_QryStr);

            }
        }
        else
        {
            this.LTV.LoadTreeView(tv_Bu, dt_BuUnit, HttpContext.Current.Request.CurrentExecutionFilePath + "?BuId=", str_QryStr);
        }
    }
    private void LoadBuData(DataTable dt_BuUnit)
    {
        DataTable dt_BuUnitData = HDD.GetDataTable("select bu_id,isnull(bu_desc,bu_id) [desc],af_row_id,owner_id,parent_bu_id  from sy_bu_unit");
        DD_parent_business_unit.DataSource = dt_BuUnitData;
        DD_parent_business_unit.DataTextField = "bu_id";
        DD_parent_business_unit.DataValueField = "af_row_id";
        DD_parent_business_unit.DataBind();
        if (Session["userid"].ToString() != "afadmin")
        {
            for (int i = DD_parent_business_unit.Items.Count - 1; i >= 0; i--)
            {
                if (DD_parent_business_unit.Items[i].Text == "CS" || DD_parent_business_unit.Items[i].Text == "ABC" || DD_parent_business_unit.Items[i].Text == "rootNode")
                    DD_parent_business_unit.Items.RemoveAt(i);

            }

        }
        if (this.str_QryStr != "")
        {
            DataRow[] drarr_BuUnit = dt_BuUnit.Select("af_row_id='" + this.str_QryStr + "'", "");
            LoadEditPage LEP = new LoadEditPage();
            HF_owner_id.Value = Convert.ToString(drarr_BuUnit[0]["owner_id"]);
            TB_owner_id.Text = LEP.GetUserIDFromAfrowid(Convert.ToString(drarr_BuUnit[0]["owner_id"]));
            ps_rowkey.Value = this.str_QryStr;
            HF_created_by.Value = Convert.ToString(drarr_BuUnit[0]["created_by"]);
            LEP = null;
            if (Request.QueryString["CPY"] != null)
            {
                //ddownerid.SelectedValue = Session["user_afrowid"].ToString();
                HF_owner_id.Value = Session["user_afrowid"].ToString();
                TB_owner_id.Text = Session["userid"].ToString();
                lblHeader.Text = "Business Unit - Copy";
                ScreenReader SR = new ScreenReader();
                TB_business_unit.Enabled = true;
                ps_rowkey.Value = SR.getHashKey();
                this.btnSave.Visible = true;
                this.btnUpdate.Visible = false;
                this.btnSaveNew.Visible = true;
            }
            TB_business_unit.Text =Server.HtmlDecode(Convert.ToString(drarr_BuUnit[0]["bu_id"]));
            TB_business_unit_desc.Text = Convert.ToString(drarr_BuUnit[0]["bu_desc"]);
            DD_hierarchy_level.SelectedValue = Convert.ToString(drarr_BuUnit[0]["text"]);
            if (Convert.ToString(drarr_BuUnit[0]["value"]) == "rootNode")
            {
                DD_parent_business_unit.Items.Add(new ListItem(Convert.ToString(drarr_BuUnit[0]["text"]), ""));
                DD_parent_business_unit.SelectedValue = "";
                DD_parent_business_unit.Enabled = false;
            }
            else
            {
                DD_parent_business_unit.SelectedValue = Convert.ToString(drarr_BuUnit[0]["parent_value"]);
            }
        }
        if (Request.QueryString["PK"] != null || Request.QueryString["BuId"] != null)
        {
            bool ischild = false;
            for (int i = DD_parent_business_unit.Items.Count - 1; i >= 0; i--)
            {
                ischild = RemoveChild(DD_parent_business_unit.Items[i].Value, dt_BuUnitData);
                if (ischild == true)
                {
                    ListItem item = DD_parent_business_unit.Items.FindByValue(DD_parent_business_unit.Items[i].Value);
                    DD_parent_business_unit.Items.Remove(item);
                }
            }

        }
    }
    private bool RemoveChild(string buId, DataTable dt_bu)
    {
        bool ischild = false;
        if (Request.QueryString["PK"] != null || Request.QueryString["BuId"] != null)
        {
            DataRow[] dr_bu = dt_bu.Select("af_row_id='" + buId + "'");
            if (dr_bu.Length > 0)
            {
                if (dr_bu[0]["parent_bu_id"].ToString() == "" | dr_bu[0]["parent_bu_id"].ToString() == ps_rowkey.Value | dr_bu[0]["af_row_id"].ToString() == ps_rowkey.Value)
                {
                    if (dr_bu[0]["parent_bu_id"].ToString() == ps_rowkey.Value | dr_bu[0]["af_row_id"].ToString() == ps_rowkey.Value)
                        ischild = true;
                }
                else
                {
                    dr_bu = dt_bu.Select("af_row_id='" + dr_bu[0]["parent_bu_id"].ToString() + "'");
                    if (dr_bu[0]["af_row_id"].ToString() == ps_rowkey.Value)
                        ischild = true;
                    else if (buId != dr_bu[0]["parent_bu_id"].ToString())
                        ischild = RemoveChild(dr_bu[0]["parent_bu_id"].ToString(), dt_bu);
                }
            }
        }
        return ischild;
    }
    
    protected void btnUpdate_ServerClick(object sender, EventArgs e)
    {
        try
        {
            DataTable DT_parent_bu = HDD.GetDataTable("Select * from sy_bu_unit where parent_bu_id='" + ps_rowkey.Value + "'");

            if (DT_parent_bu != null && DT_parent_bu.Rows.Count > 0)
            {
                for (int i = 0; i < DT_parent_bu.Rows.Count; i++)
                {
                    if (DD_parent_business_unit.SelectedValue.ToString() == DT_parent_bu.Rows[i]["af_row_id"].ToString())
                    {
                        lblMessage.Text = ErrMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Cyclic hierarchy is not allowed  " + ErrorMessage, true);
                        return;
                    }
                }
            }
            this.HDD.ExecuteTransaction(DeleteAndInsertCmd());
            Response.Redirect("DisplayGrid.aspx?mn=" + HDD.GetColumnValue("sy_mnu", "af_row_id", "pageset_id = '896d3320756939fe' and pageset_url = 'BusinessUnitConfig.aspx'") + "&pgs_id=896d3320756939fe", true); // pageset_id and pgs_id=bu_unit
        }
        catch (Exception Ex)
        {
            throw Ex;
        }
    }
    protected void btnReset_ServerClick(object sender, EventArgs e)
    {
        //try
        //{
        //    if (str_QryStr != "")
        //    {
        //        Response.Redirect("DisplayGrid.aspx?mn=" + HDD.GetColumnValue("sy_mnu", "menu_id", "pageset_id = '896d3320756939fe' and pageset_url = 'BusinessUnitConfig.aspx'") + "&pgs_id=896d3320756939fe", true);
        //    }
        //    else
        //    {
        //        TB_business_unit.Text = "";
        //        TB_business_unit_desc.Text = "";
        //        DD_hierarchy_level.SelectedIndex = 0;
        //        DD_parent_business_unit.SelectedIndex = 0;
        //    }
        //}
        //catch (Exception Ex)
        //{
        //    throw Ex;
        //}
    }
    private ArrayList DeleteAndInsertCmd()
    {
        if (this.str_QryStr == "")
        {
            string str_BuUnit = this.HDD.GetColumnValue("sy_bu_unit", "bu_id", "bu_id='" + TB_business_unit.Text + "'");
            if (str_BuUnit != "")
            {
                Response.Redirect("DisplayGrid.aspx?mn=" + HDD.GetColumnValue("sy_mnu", "af_row_id", "pageset_id = '896d3320756939fe' and pageset_url = 'BusinessUnitConfig.aspx'") + "&pgs_id=896d3320756939fe", true); // pageset_id and pgs_id=bu_unit
            }
        }
        ArrayList arl_BusinessUnit = new ArrayList();
        SqlCommand sco_Delete = new SqlCommand();
        sco_Delete.CommandText = "delete from sy_bu_unit where af_row_id=@af_row_id";
        sco_Delete.Parameters.AddWithValue("@af_row_id", ps_rowkey.Value);
        arl_BusinessUnit.Add(sco_Delete);
        string str_InsertQry = "insert into sy_bu_unit(af_row_id,bu_id,bu_desc,parent_bu_id,hierarchy_level,"
        + "created_by,modified_by,owner_id,created_at,modified_at) values "
        + "(@af_row_id,@bu_id,@bu_desc,@parent_bu_id,@hierarchy_level,"
        + "@created_by,@modified_by,@owner_id,@created_at,@modified_at)";
        SqlCommand sco_Insert = new SqlCommand(str_InsertQry);
        sco_Insert.Parameters.AddWithValue("@bu_id", Server.HtmlEncode(TB_business_unit.Text).Replace(":", "").Replace("#", ""));
        sco_Insert.Parameters.AddWithValue("@af_row_id", ps_rowkey.Value);
        sco_Insert.Parameters.AddWithValue("@bu_desc", TB_business_unit_desc.Text);
        sco_Insert.Parameters.AddWithValue("@parent_bu_id", DD_parent_business_unit.SelectedValue);
        sco_Insert.Parameters.AddWithValue("@hierarchy_level", DD_hierarchy_level.SelectedValue);
        sco_Insert.Parameters.AddWithValue("@owner_id", HF_owner_id.Value);
        if (HF_created_by.Value != "")
        {
            sco_Insert.Parameters.AddWithValue("@created_by", HF_created_by.Value);
        }
        else
        {
            sco_Insert.Parameters.AddWithValue("@created_by", HF_owner_id.Value);
        }
        sco_Insert.Parameters.AddWithValue("@modified_by", HF_owner_id.Value);
        sco_Insert.Parameters.AddWithValue("@created_at", DateTime.Now);
        sco_Insert.Parameters.AddWithValue("@modified_at", DateTime.Now);
        arl_BusinessUnit.Add(sco_Insert);
        return arl_BusinessUnit;
    }
    private string ErrMessage(string msg, bool isError)
    {
        return "<div class=\"" + (isError == true ? "mbErrorMessage" : "mbMessage") + "\">" + msg + "</div>";
    }
    public string ErrorMessage
    {
        get
        {
            return this.strErrMessage;
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (Request.QueryString["CPY"] != null)
            {
                this.str_QryStr = "";
            }
            if (this.str_QryStr == "")
            {
                string str_BuUnit = this.HDD.GetColumnValue("sy_bu_unit", "bu_id", "bu_id='" + TB_business_unit.Text + "'");
                if (str_BuUnit != "")
                {
                    //july
                    //Response.Redirect("DisplayGrid.aspx?mn=" + HDD.GetColumnValue("sy_mnu", "menu_id", "pageset_id = '896d3320756939fe' and pageset_url = 'BusinessUnitConfig.aspx'") + "&pgs_id=896d3320756939fe", true);
                    lblMessage.Text = ErrMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Business unit Id already exist  " + ErrorMessage, true);
                    return;
                }
            }
            DataTable DT_parent_bu = HDD.GetDataTable("Select * from sy_bu_unit where parent_bu_id='" + ps_rowkey.Value + "'");

            if (DT_parent_bu != null && DT_parent_bu.Rows.Count > 0)
            {
                for (int i = 0; i < DT_parent_bu.Rows.Count; i++)
                {
                    if (DD_parent_business_unit.SelectedValue == DT_parent_bu.Rows[i]["af_row_id"])
                    {
                        lblMessage.Text = ErrMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Cyclic hierarchy is not allowed  " + ErrorMessage, true);
                        return;
                    }
                }
            }
            this.HDD.ExecuteTransaction(DeleteAndInsertCmd());
            Response.Redirect("DisplayGrid.aspx?mn=" + HDD.GetColumnValue("sy_mnu", "af_row_id", "pageset_id = '896d3320756939fe' and pageset_url = 'BusinessUnitConfig.aspx'") + "&pgs_id=896d3320756939fe", true); // pageset_id and pgs_id=bu_unit
        }
        catch (Exception Ex)
        {
            throw Ex;
        }

    }
    protected void btnSaveNew_Click(object sender, EventArgs e)
    {
        try
        {
            //if (TB_business_unit.Text != "" | TB_business_unit_desc.Text != "")
            //{
            if (Request.QueryString["CPY"] != null)
            {
                this.str_QryStr = "";
            }
            if (this.str_QryStr == "")
            {
                string str_BuUnit = this.HDD.GetColumnValue("sy_bu_unit", "bu_id", "bu_id='" + TB_business_unit.Text + "'");
                if (str_BuUnit != "")
                {
                    //july
                    //Response.Redirect("DisplayGrid.aspx?mn=" + HDD.GetColumnValue("sy_mnu", "menu_id", "pageset_id = '896d3320756939fe' and pageset_url = 'BusinessUnitConfig.aspx'") + "&pgs_id=896d3320756939fe", true);
                    lblMessage.Text = ErrMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Business unit Id already exist  " + ErrorMessage, true);
                    return;
                }
            }

            DataTable DT_parent_bu = HDD.GetDataTable("Select * from sy_bu_unit where parent_bu_id='" + ps_rowkey.Value + "'");

            if (DT_parent_bu != null && DT_parent_bu.Rows.Count > 0)
            {
                for (int i = 0; i < DT_parent_bu.Rows.Count; i++)
                {
                    if (DD_parent_business_unit.SelectedValue == DT_parent_bu.Rows[i]["af_row_id"])
                    {
                        lblMessage.Text = ErrMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Cyclic hierarchy is not allowed  " + ErrorMessage, true);
                        return;
                    }
                }
            }
            this.HDD.ExecuteTransaction(DeleteAndInsertCmd());
            Response.Redirect("BusinessUnitConfig.aspx?mn=" + HDD.GetColumnValue("sy_mnu", "af_row_id", "pageset_id = '896d3320756939fe' ") + "&pgs_id=896d3320756939fe", true); // pageset_id and pgs_id=bu_unit
            //}
            //else
            //{
            //    ClientScript.RegisterStartupScript(this.GetType(), "", "Please Enter all mandatory fields");
            //    return;
            //}
        }
        catch (Exception Ex)
        {
            throw Ex;
        }

    }
}
